/*
 * datatandroid - Persistence framework for Android platform
 * 
 * Copyright (C) 2010 ProjectsException
 * <http://code.google.com/p/datandroid>
 * 
 * This file is part of datatandroid.
 * 
 * datatandroid is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * datatandroid is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with datatandroid.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.projectsexception.datandroid;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.xmlpull.v1.XmlPullParserException;

import android.content.res.XmlResourceParser;

import com.projectsexception.datandroid.database.BasicProperty;
import com.projectsexception.datandroid.database.CollectionBasicProperty;
import com.projectsexception.datandroid.database.CollectionEntityProperty;
import com.projectsexception.datandroid.database.Database;
import com.projectsexception.datandroid.database.Entity;
import com.projectsexception.datandroid.database.EntityProperty;
import com.projectsexception.datandroid.database.IBasicProperty;
import com.projectsexception.datandroid.database.ICollectionProperty;
import com.projectsexception.datandroid.database.IProperty;
import com.projectsexception.datandroid.util.DatabaseUtil;
import com.projectsexception.datandroid.util.DatandroidConfigurationException;
import com.projectsexception.datandroid.util.ReflectionUtil;

public class DatandroidSetup {
    
    private Set<String> unexpectedClasses;
    private Set<String> analizedClasses;
    private Entity entity;
    private Map<String, Class<?>> entityAttributes;
    
    public DatandroidSetup() {
        unexpectedClasses = new HashSet<String>();
        analizedClasses = new HashSet<String>();
        entity = null;
        entityAttributes = null;
    }
    
    public Database parseConfigFile(XmlResourceParser res) throws DatandroidException {
        Database database = new Database();
        Map<String, Entity> entities = new HashMap<String, Entity>();
        database.setEntities(entities);
        try {
            while (res.getEventType() != XmlResourceParser.END_DOCUMENT) {
                if (res.getEventType() == XmlResourceParser.START_TAG) {
                    if (res.getName().equals("database")) {
                        database.setName(res.getAttributeValue(null, "name"));
                        database.setVersion(Integer.parseInt(res.getAttributeValue(null, "version")));
                    } else if (res.getName().equals("entity")) {
                        Class<?> clazz = checkClassName(res.getAttributeValue(null, "class"));
                        entity = createEntity(clazz, res.getAttributeValue(null, "tableName"));
                        entityAttributes = ReflectionUtil.classAttributes(clazz);
                    } else if (res.getName().equals("id")) {
                        entity.setIdProperty(createIdProperty(res.getAttributeValue(null, "name"), 
                                res.getAttributeValue(null, "class"), res.getAttributeValue(null, "column")));
                    } else if (res.getName().equals("property")) {
                        entity.getProperties().add(createProperty(res.getAttributeValue(null, "name"), res.getAttributeValue(null, "class"), 
                                res.getAttributeValue(null, "column"), res.getAttributeValue(null, "allowNull"), res.getAttributeValue(null, "deleteCascade")));
                    } else if (res.getName().equals("one-to-many")) {
                        entity.getProperties().add(createColProperty(res.getAttributeValue(null, "name"), res.getAttributeValue(null, "classItem"), 
                                res.getAttributeValue(null, "table"), res.getAttributeValue(null, "column"), res.getAttributeValue(null, "allowNull")));
                    }
                } else if (res.getEventType() == XmlResourceParser.TEXT) {
//                    text
                } else if (res.getEventType() == XmlResourceParser.END_TAG) {
                    if (res.getName().equals("entity")) {
                        if (entity.getIdProperty() == null) {
                            throw new DatandroidConfigurationException("Mandatory <id> element not found in entity class " + entity.getClassName());
                        }
                        fillProperties();
                        entities.put(entity.getClassName(), entity);
                    }
                }
                res.next();
            }
        } catch (XmlPullParserException e) {
            throw new DatandroidConfigurationException(e);
        } catch (IOException e) {
            throw new DatandroidConfigurationException(e);            
        } finally {
            res.close();
        }
        if (!unexpectedClasses.isEmpty()) {
            throw new DatandroidConfigurationException("Founded entities not configured: " + unexpectedClasses);
        }
        return database;
    }
    
    private Entity createEntity(Class<?> clazz, String tableName) throws DatandroidException {
        if (DatabaseUtil.isBasicType(clazz)) {
            throw new DatandroidConfigurationException("Class entity " + clazz.getName() + " is a basic type");
        }
        analizedClasses.add(clazz.getName());
        if (unexpectedClasses.contains(clazz.getName())) {
            unexpectedClasses.remove(clazz.getName());
        }
        Entity entity = new Entity();
        entity.setClassName(clazz.getName());
        if (isEmpty(tableName)) {
            entity.setTableName(clazz.getSimpleName());
        } else {
            entity.setTableName(tableName);
        }
        entity.setProperties(new ArrayList<IProperty>());
        return entity;
    }
    
    private IBasicProperty createIdProperty(String name, String className, String columnName) throws DatandroidException {
        Class<?> clazz = entityAttributes.get(name);
        if (clazz == null) {
            throw new DatandroidConfigurationException("Property " + name + " not found in entity " + entity.getClassName());
        }
        if (!isEmpty(className) && !className.equals(clazz.getName())) {
            throw new DatandroidConfigurationException("Property " + name + " with class" + className + " not aplicable to " + clazz.getName());
        }
        if (!DatabaseUtil.isBasicType(clazz)) {
            throw new DatandroidConfigurationException("ID with class " + className + " is a basic type");
        }
        IBasicProperty prop = new BasicProperty();
        prop.setName(name);
        prop.setClassName(clazz.getName());
        if (isEmpty(columnName)) {
            prop.setColumnName(name);
        } else {
            prop.setColumnName(columnName);
        }
        prop.setAllowNull(false);
        return prop;
    }
    
    private IProperty createProperty(String name, String className, String columnName, String allowNull, String deleteCascade) throws DatandroidException {
        Class<?> clazz = entityAttributes.get(name);
        if (clazz == null) {
            throw new DatandroidConfigurationException("Property " + name + " not found in entity " + entity.getClassName());
        }
        if (!isEmpty(className) && !className.equals(clazz.getName())) {
            throw new DatandroidConfigurationException("Property " + name + " with class " + className + " not aplicable to " + clazz.getName());
        }
        IBasicProperty prop;
        if (DatabaseUtil.isBasicType(clazz)) {
            prop = new BasicProperty();
        } else {
            prop = new EntityProperty();
            boolean cascade = Boolean.parseBoolean(deleteCascade);
            if (deleteCascade == null) {
                cascade = true;
            }
            ((EntityProperty) prop).setDeleteCascade(cascade);
        }
        prop.setName(name);
        prop.setClassName(clazz.getName());
        if (isEmpty(columnName)) {
            prop.setColumnName(name);
        } else {
            prop.setColumnName(columnName);
        }
        prop.setAllowNull(Boolean.parseBoolean(allowNull));        
        return prop;
    }
    
    private ICollectionProperty createColProperty(String name, String classItem, String tableName, String columnName, String allowNull) throws DatandroidException {
        Class<?> clazz = entityAttributes.get(name);
        if (clazz == null) {
            throw new DatandroidConfigurationException("Property " + name + " not found in entity " + entity.getClassName());
        }
        if (!java.util.Collection.class.isAssignableFrom(clazz)) {
            throw new DatandroidConfigurationException("Property " + name + " is not a collection");
        }
        if (isEmpty(classItem)) {
            throw new DatandroidConfigurationException("Attibute 'classItem' required for property " + name
                    + " in entity " + entity.getClassName());
        }
        Class<?> classItemObj = checkClassName(classItem);
        ICollectionProperty prop;
        if (DatabaseUtil.isBasicType(classItemObj)) {
            prop = new CollectionBasicProperty();
            if (isEmpty(tableName)) {
                ((CollectionBasicProperty) prop).setTableName(entity.getTableName() + "_" + prop.getName());
            } else {
                ((CollectionBasicProperty) prop).setTableName(tableName);            
            }
        } else {
            prop = new CollectionEntityProperty();
            if (isEmpty(columnName)) {
                ((CollectionEntityProperty) prop).setColumnName(entity.getTableName() + "_ID");
            } else {
                ((CollectionEntityProperty) prop).setColumnName(columnName);                
            }
        }
        prop.setName(name);
        prop.setClassItem(classItem);
        prop.setClassName(clazz.getName());
        prop.setAllowNull(Boolean.parseBoolean(allowNull));
        return prop;
    }
    
    private void fillProperties() throws DatandroidException {
        // Completamos las propiedades y relaciones que no estén especificadas
        for (String attribute : entityAttributes.keySet()) {
            boolean found = entity.getIdProperty().getName().equals(attribute);                
            if (!found && entity.getProperties() != null) {
                for (IProperty prop : entity.getProperties()) {
                    if (attribute.equals(prop.getName())) {
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {                
                Class<?> propClass = entityAttributes.get(attribute);
                if (propClass.isAssignableFrom(java.util.Collection.class)) {
                    throw new DatandroidConfigurationException("Found a property that is a collection and is not mapped");
                }
                IBasicProperty prop;
                if (DatabaseUtil.isBasicType(propClass)) {
                    prop = new BasicProperty();
                } else {
                    if (!analizedClasses.contains(propClass.getName())) {
                        unexpectedClasses.add(propClass.getName());
                    }
                    prop = new EntityProperty();                    
                }
                prop.setName(attribute);
                prop.setColumnName(attribute);
                prop.setClassName(propClass.getName());
                prop.setAllowNull(false);
                entity.getProperties().add(prop);                    
            }
        }
    }
    
    private Class<?> checkClassName(String className) throws DatandroidException {
        if (isEmpty(className)) {
            throw new DatandroidConfigurationException("Property attribute class can't be empty");
        }
        try {
            Class<?> clazz = Class.forName(className);
            if (!DatabaseUtil.isBasicType(className) && !java.util.Collection.class.isAssignableFrom(clazz)) {
                if (!analizedClasses.contains(className)) {
                    unexpectedClasses.add(className);                    
                }
            }
            return clazz;
        } catch (ClassNotFoundException e) {
            throw new DatandroidConfigurationException(e.getLocalizedMessage());
        }
    }

    private static boolean isEmpty(String string) {
        return string == null || string.trim().length() == 0;
    }

}
